from rest_framework.viewsets import ModelViewSet
from meiduo_admin.utils import MyNumbPage, upload_image
from goods.models import Brand
from .serializers import BrandSerializer
from rest_framework.response import Response


class BrandViewSet(ModelViewSet):
    serializer_class = BrandSerializer
    queryset = Brand.objects.all()
    pagination_class = MyNumbPage

    def create(self, request, *args, **kwargs):
        data = request.data
        name = data.get('name')
        logo = data.get('logo')
        first_letter = data.get('first_letter')
        logo = upload_image(logo)
        if not logo:
            return Response(status=400)
        Brand.objects.create(name=name, logo=logo, first_letter=first_letter)

        return Response(status=201)

    def update(self, request, *args, **kwargs):
        obj = self.get_object()
        data = request.data
        name = data.get('name')
        logo = data.get('logo')
        first_letter = data.get('first_letter')
        logo = upload_image(logo)
        if not logo:
            return Response(status=400)
        obj.name = name
        obj.logo = logo
        obj.first_letter = first_letter
        obj.save()

        return Response(status=201)
